﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit.Design;
using AjaxControlToolkit;
using System.Data;
using BCDataCenter;
using BCDataCenter.BOL;
using CSharp_MessageBox;
using System.Data.SqlClient;

public partial class WebUserControl_TraHangUngDiShow : System.Web.UI.UserControl
{
    DataTable dtChiTietDH;
    string error = "";
    BCDataCenter.DataAccessLayer.DAL dt;
    ClassExecute.ClassExecute dtEx;
    string str = BCDataCenter.Configuration.CurrentConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            Session["dtChiTietDHTra"] = null;
            FillGrid();
            CheckReadOnly();
            FillGridHoaDonChuaIn();
            
        }
        if (gvChiTietDonHang.Rows[0].Cells[0].Text == "Thêm mặt hàng vào hóa đơn")
        {
            int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
            gvChiTietDonHang.Rows[0].Cells.Clear();
            gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
            gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
            txtTongTien.Text = "0";
        }
        
    }
    public void CheckReadOnly()
    {
        dtEx = new ClassExecute.ClassExecute();
        int i = dtEx.ExecuteSQl_int(str, "[ls_isAllowedChooseInvDate]", CommandType.StoredProcedure, ref error,
            new SqlParameter("@siteCode", Session["sitecode"].ToString()));
        if (i == 0)
        {

            txtNgayHD.Enabled = false;
            txtNgayHD.Text = DateTime.Now.ToString("dd/MM/yyyy");
            // GetMinDay();
        }
        else
        {
            txtNgayHD.ReadOnly = false;
            string ClosedDate = dtEx.GetDataDepend(str, "[ls_getClosedDate]", CommandType.StoredProcedure, ref error,
                new SqlParameter("@siteCode", Session["sitecode"].ToString()));
            DateTime date;
            System.Globalization.DateTimeFormatInfo sFormat = new System.Globalization.DateTimeFormatInfo();
            sFormat.ShortDatePattern = "dd/MM/yyyy";
            date = Convert.ToDateTime(ClosedDate, sFormat);
            Session["MinDate"] = date.AddDays(1);
            txtNgayHD.Text = date.AddDays(1).ToString("dd/MM/yyyy");

        }
    }
    protected void txtNgayHD_TextChanged(object sender, EventArgs e)
    {
        try
        {
            DateTime date_min = DateTime.Parse(txtNgayMinHD.Value, new CultureInfo("fr-FR", false)).AddDays(1);
            DateTime date_NgayHD = DateTime.Parse(txtNgayHD.Text, new CultureInfo("fr-FR", false));
            if (date_NgayHD < date_min)
            {
                txtNgayHD.Text = date_min.ToString("dd/MM/yyyy");
                uscMsgBox1.AddMessage("Ngày hóa đơn nhỏ hơn ngày khóa sổ '" + date_min.ToString("dd/MM/yyyy") + "'", uscMsgBox.enmMessageType.Error);
                FillGrid();
            }            
        }
        catch
        { return; }
    }
    private void GetMinDay()
    {
        BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
        try
        {
            txtNgayMinHD.Value = obj.dsMinDay(ref error, Session["Sitecode"].ToString()).Tables[0].Rows[0]["Closed Date"].ToString();

        }
        catch
        { return; }
    }
    private string GetMaHD()
    {
        string MaHD = "";
        try
        {
            BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
            MaHD = obj.dsMatHD(ref error).Tables[0].Rows[0]["MaHD"].ToString();
        }
        catch
        { return MaHD; }
        return MaHD;
    }
    private void GetDoanhSoTrongThangTVV(string salesp_key)
    {
        dtEx = new ClassExecute.ClassExecute();
        DataTable dbget = dtEx.Get_Data_DataTable(str, ref error, "ls_getBAMTDInfor", CommandType.StoredProcedure,
            new SqlParameter("@SalesPKey", salesp_key));
        if (dbget.Rows.Count > 0)
        {
            txtDSTrongThang.Text = dbget.Rows[0]["DoanhSoTrongThang"].ToString();
            txtDSTN.Text = dbget.Rows[0]["DoanhSoToanNhom"].ToString();
            txtSoBA.Text = dbget.Rows[0]["SoBAToanNhom"].ToString();
        }
    }
    private bool CheckValid()
    {
        BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
        if (obj.IsExistMaHD(ref error, txtSoHD.Text))
        {
            txtSoHD.Text = GetMaHD();
            uscMsgBox1.AddMessage("Số hóa đơn [" + txtSoHD.Text + "] này đã tồn tại.Bạn phải lưu với số hóa đơn mới [" + obj.dsMatHD(ref error).Tables[0].Rows[0]["MaHD"].ToString() + "]!", uscMsgBox.enmMessageType.Error);
            return false;
        }
        else if (txtMaTVV.Text == "" || txtMaTVV.Text == "null")
        {
            uscMsgBox1.AddMessage("Chưa chọn hóa đơn của tư vấn viên.", uscMsgBox.enmMessageType.Error);
            return false;
            //lbMsg.Text = "Số hóa đơn [" + txtSoHD.Text + "] này đã tồn tại.Bạn có muốn lưu với số hóa đơn mới [" + obj.dsMatHD(ref error).Tables[0].Rows[0]["MaHD"].ToString() + "] không?";
        }
        else if (!obj.IsExistTVV(ref error, txtMaTVV.Text))
        {
            uscMsgBox1.AddMessage("Mã tư vấn viên này không tồn tại.", uscMsgBox.enmMessageType.Error);
            return false;
        }

        return true;
    }
    private void FillGridHoaDonChuaIn()
    {
        try
        {
            if (Session["Sitecode"] != null)
            {
                BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
                DataTable dt = obj.dsHoaDonTraHangChuaIn(ref error, Session["Sitecode"].ToString(), 1).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    gvDonHangChuaIn.DataSource = dt;
                    gvDonHangChuaIn.DataBind();
                }
                else
                {
                    dt.Rows.Add(dt.NewRow());
                    gvDonHangChuaIn.DataSource = dt;
                    gvDonHangChuaIn.DataBind();

                    int TotalColumns = gvDonHangChuaIn.Rows[0].Cells.Count;
                    gvDonHangChuaIn.Rows[0].Cells.Clear();
                    gvDonHangChuaIn.Rows[0].Cells.Add(new TableCell());
                    gvDonHangChuaIn.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                    gvDonHangChuaIn.Rows[0].Cells[0].Text = "Không có đơn hàng chưa in.";
                }

            }
        }
        catch { return; }
    }
    private DataTable dtChiTietDonHang()
    {
        DataTable dtChiTietDH = new DataTable();
        DataColumn dtc;
        //Tao Cot Thu Tu
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "STT";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Loai Dong
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "LoaiDong";
        dtChiTietDH.Columns.Add(dtc);
        //Tao Cot Ma Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "MaHang";
        dtChiTietDH.Columns.Add(dtc);
        //Tao Cot Ten Hang
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "TenHang";
        dtChiTietDH.Columns.Add(dtc);
        //Tao Cot So Luong
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "SoLuong";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot Gia
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "Gia";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot VAT
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "VAT";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot ThanhTien
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "ThanhTien";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot MaVAT
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "MaVAT";
        dtChiTietDH.Columns.Add(dtc);

        //Tao Cot loaiKM
        dtc = new DataColumn();
        dtc.DataType = Type.GetType("System.String");
        dtc.ColumnName = "ProgramType";
        dtChiTietDH.Columns.Add(dtc);

        return dtChiTietDH;
    }   
    protected void btnSave_Click(object sender, ImageClickEventArgs e)
    {
        //Session["dtChiTietDHTra"] = null;
        BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
        dt = new BCDataCenter.DataAccessLayer.DAL();
        string MaHD = "";
        MaHD = GetMaHD();
        try
        {
            if (txtSoHD.Text == "")
            {
                if (CheckValid())
                {
                    float fTongHD = 0;
                    if (txtTongTien.Text != "")
                    {
                        fTongHD = float.Parse(txtTongTien.Text);
                    }
                    DateTime daytimeNow = DateTime.Now;
                    if (obj.InsertHoaDonTraHangCuaNhomTruong(ref error, Session["Sitecode"].ToString(), MaHD, txtMaTVV.Text, Session["username"].ToString(), fTongHD, txtNgayHD.Text, daytimeNow))
                    {
                        dtChiTietDH = (DataTable)Session["dtChiTietDHTra"];
                        int n = dtChiTietDH.Rows.Count;
                        int cout = 0;
                        string DongHang = "";
                        string MaKho = obj.getMaKho(ref error, Session["Sitecode"].ToString());
                        for (int i = 0; i < n; i++)
                        {
                            DongHang = dtChiTietDH.Rows[i]["LoaiDong"].ToString();
                            if (DongHang == "")
                                DongHang = "0";
                            string MaHang = dtChiTietDH.Rows[i]["MaHang"].ToString();
                            
                            
                            if (obj.InsertCTHoaDonTraHangTVV(ref error, Session["Sitecode"].ToString(), MaHD, daytimeNow, Session["username"].ToString(),
                                txtNgayHD.Text, MaHang, dtChiTietDH.Rows[i]["TenHang"].ToString(), DongHang,
                                dtChiTietDH.Rows[i]["MaVAT"].ToString(), float.Parse(dtChiTietDH.Rows[i]["SoLuong"].ToString()), float.Parse(dtChiTietDH.Rows[i]["Gia"].ToString()),
                                int.Parse(dtChiTietDH.Rows[i]["STT"].ToString())))
                            {
                                cout++;
                            }
                            else
                            {
                                obj.DeleteCTHoaDonBanHangTVV(ref error, MaHD);
                                obj.DeleteHoaDonBanHangTVV(ref error, MaHD);
                                uscMsgBox1.AddMessage("Không thể lưu hóa đơn này.\n Lỗi: " + error, uscMsgBox.enmMessageType.Error);
                                break;
                            }                                
                        }
                        if (cout == n)
                        {
                            txtSoHD.Text = MaHD;
                            FillGridHoaDonChuaIn();
                            uscMsgBox1.AddMessage("Lưu hóa đơn thành công", uscMsgBox.enmMessageType.Success);
                            //------phan A.Phu lam them
                            //BCDataCenter.DataAccessLayer.DAL them = new BCDataCenter.DataAccessLayer.DAL();
                            //them.IsExistFromSQL("update ARHDR set doctot =" + float.Parse(txtTongTien.Text) + "where tranno ='" + MaHD + "'", CommandType.Text, ref error);
                        }
                    }
                }
            }
            else //Update
            {
                //bool flagVuotTon = false;
                DataTable dtCTHD = new DataTable();
                dtCTHD = (DataTable)Session["dtChiTietDHTra"];
                //string VuotTon = "";
                string DongHang = "";
                string MaKho = obj.getMaKho(ref error, Session["Sitecode"].ToString());                

                DateTime DateTimeNow = DateTime.Now;
                string Sitecode = Session["Sitecode"].ToString();
                string UserName = Session["username"].ToString();

                //MaHD, NgayHD
                DataColumn dtc;
                //Tao Cot DateTimeNow
                if (!dtCTHD.Columns.Contains("DateTimeNow"))
                {
                    dtc = new DataColumn();
                    dtc.DataType = Type.GetType("System.String");
                    dtc.ColumnName = "DateTimeNow";
                    dtCTHD.Columns.Add(dtc);
                }
                if (!dtCTHD.Columns.Contains("Sitecode"))
                {
                    dtc = new DataColumn();
                    dtc.DataType = Type.GetType("System.String");
                    dtc.ColumnName = "Sitecode";
                    dtCTHD.Columns.Add(dtc);
                }
                if (!dtCTHD.Columns.Contains("UserName"))
                {
                    dtc = new DataColumn();
                    dtc.DataType = Type.GetType("System.String");
                    dtc.ColumnName = "UserName";
                    dtCTHD.Columns.Add(dtc);
                }
                if (!dtCTHD.Columns.Contains("MaHD"))
                {
                    dtc = new DataColumn();
                    dtc.DataType = Type.GetType("System.String");
                    dtc.ColumnName = "MaHD";
                    dtCTHD.Columns.Add(dtc);
                }
                if (!dtCTHD.Columns.Contains("NgayHD"))
                {
                    dtc = new DataColumn();
                    dtc.DataType = Type.GetType("System.String");
                    dtc.ColumnName = "NgayHD";
                    dtCTHD.Columns.Add(dtc);
                }

                for (int i = 0; i < dtCTHD.Rows.Count; i++)
                {
                    dtCTHD.Rows[i]["DateTimeNow"] = DateTimeNow;
                    dtCTHD.Rows[i]["Sitecode"] = Sitecode;
                    dtCTHD.Rows[i]["UserName"] = UserName;
                    dtCTHD.Rows[i]["MaHD"] = txtSoHD.Text;
                    dtCTHD.Rows[i]["NgayHD"] = txtNgayHD.Text;
                    if (dtCTHD.Rows[i]["LoaiDong"].ToString() == "")
                    {
                        dtCTHD.Rows[i]["LoaiDong"] = "0";
                    }
                }
                if (obj.UpdateChiTietHDTraTVV(ref error, txtSoHD.Text, dtCTHD))
                {
                    if (obj.UpdateHoaDonTVV(ref error, txtSoHD.Text, float.Parse(txtTongTien.Text), txtNgayHD.Text, DateTime.Now))
                    {
                        FillGridHoaDonChuaIn();
                        uscMsgBox1.AddMessage("Cập nhật đơn hàng chi tiết đơn hàng thành công", uscMsgBox.enmMessageType.Success);
                        BCDataCenter.DataAccessLayer.DAL them = new BCDataCenter.DataAccessLayer.DAL();
                        them.IsExistFromSQL("update ARHDR set doctot =" + float.Parse(txtTongTien.Text) + "where tranno ='" + txtSoHD.Text.ToString() + "'", CommandType.Text, ref error);

                    }
                    else
                    {
                        uscMsgBox1.AddMessage("Cập nhật đơn hàng và chi tiết đơn hàng thất bại", uscMsgBox.enmMessageType.Success);
                    }
                }
                else
                {
                    uscMsgBox1.AddMessage("Cập nhật đơn hàng và chi tiết đơn hàng thất bại.\n Error: ", uscMsgBox.enmMessageType.Error);
                }
                
            }
        }
        catch (Exception ex)
        {
            obj.DeleteCTHoaDonBanHangTVV(ref error, MaHD);
            obj.DeleteHoaDonBanHangTVV(ref error, MaHD);
            uscMsgBox1.AddMessage(error + "\n Eror:" + ex, uscMsgBox.enmMessageType.Error);
            return;
        }
    }
    protected void btnNew_Click(object sender, ImageClickEventArgs e)
    {
        Session["dtChiTietDHTra"] = null;
        Session["dtChiTietDHKhuyenMai"] = null;
        txtSoHD.Text = "";
        txtMaTVV.Text = "";
        txtTenTVV.Text = "";
        txtThongTinTVV.Text = "";
        txtMaTVV.Enabled = true;
        btnDelete.Visible = false;
        //GetMaHD();
        txtNgayHD.Text = DateTime.Now.ToString("dd/MM/yyyy");

        FillGrid();
    }
    protected void btnDelete_Click(object sender, ImageClickEventArgs e)
    {

        //GetMaHD();
        //txtNgayHD.Text = DateTime.Now.ToString("dd/MM/yyyy");
        if (txtSoHD.Text == "")
        {
            uscMsgBox1.AddMessage("Bạn chưa chọn hóa đơn cần xóa", uscMsgBox.enmMessageType.Error);
        }
        else
        {
            BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
            if (obj.DeleteHoaDonVaCTHDBanHangTVV(ref error, txtSoHD.Text))
            {
                uscMsgBox1.AddMessage("Xóa hóa đơn số [" + txtSoHD.Text + "] thành công", uscMsgBox.enmMessageType.Success);
                Session["dtChiTietDHTra"] = null;
                //Session["dtChiTietDHKhuyenMai"] = null;
                txtSoHD.Text = "";
                btnDelete.Visible = false;
                FillGrid();
                FillGridHoaDonChuaIn();


            }
            else
            {
                uscMsgBox1.AddMessage("Xóa hóa đơn số [" + txtSoHD.Text + "] thất bại.\n Lỗi: \n" + error, uscMsgBox.enmMessageType.Success);
            }
        }

    }
    private void FillGrid()
    {
        try
        {
            DataTable dt = new DataTable();
            if (Session["dtChiTietDHTra"] == null)
            {
                dt = dtChiTietDonHang();
                Session["dtChiTietDHTra"] = dtChiTietDH;
            }
            else
                dt = (DataTable)Session["dtChiTietDHTra"];
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows.Count == 1 && dt.Rows[0]["MaHang"].ToString().Equals(String.Empty))
                {
                    gvChiTietDonHang.DataSource = dt;
                    gvChiTietDonHang.DataBind();

                    int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
                    gvChiTietDonHang.Rows[0].Cells.Clear();
                    gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
                    gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                    gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
                    txtTongTien.Text = "0";
                }
                else
                {
                    gvChiTietDonHang.DataSource = dt;
                    gvChiTietDonHang.DataBind();
                    if (TongTienHoaDon(dt, "ThanhTien") == 0)
                    {
                        txtTongTien.Text = "0";
                    }
                    else
                    {
                        txtTongTien.Text = String.Format("{0:###,###}", TongTienHoaDon(dt, "ThanhTien"));
                    }                    
                }
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                gvChiTietDonHang.DataSource = dt;
                gvChiTietDonHang.DataBind();

                int TotalColumns = gvChiTietDonHang.Rows[0].Cells.Count;
                gvChiTietDonHang.Rows[0].Cells.Clear();
                gvChiTietDonHang.Rows[0].Cells.Add(new TableCell());
                gvChiTietDonHang.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gvChiTietDonHang.Rows[0].Cells[0].Text = "Thêm mặt hàng vào hóa đơn";
                txtTongTien.Text = "0";
            }
        }
        catch { return; }
    }
    private double TongTienHoaDon(DataTable dtChiTietHoaDon, string ColumnName)
    {
        double dTongTien = 0;
        if (dtChiTietHoaDon.Rows.Count > 0)
        {
            for (int i = 0; i < dtChiTietHoaDon.Rows.Count; i++)
            {
                if (dtChiTietHoaDon.Rows[i]["LoaiDong"].ToString() == "" || dtChiTietHoaDon.Rows[i]["LoaiDong"].ToString() == "0")
                {
                    dTongTien += double.Parse(dtChiTietHoaDon.Rows[i][ColumnName].ToString());
                }
            }
        }
        return System.Math.Round(dTongTien);
    }
    private void get_ListChiTietHoaDon(string MaDH,string store)
    {
        try
        {
            dtEx = new ClassExecute.ClassExecute();
            //thay thế cái này bằng
            //Session["dtChiTietDHTra"] = dtEx.Get_Data_DataSet(str, ref error, "get_ChiTietHoaDonTraChuaIn", CommandType.StoredProcedure,
            //    new SqlParameter("@tranno", MaDH)).Tables[0];
            //get_ChiTietHoaDonTra
            Session["dtChiTietDHTra"] = dtEx.Get_Data_DataSet(str, ref error, store, CommandType.StoredProcedure,
               new SqlParameter("@tranno", MaDH)).Tables[0];
            txtSoHD.Text = MaDH;
            FillGrid();
        }
        catch { return; }
    }
    protected void gvDonHangChuaIn_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            GridViewRow gvr = ((Control)e.CommandSource).NamingContainer as GridViewRow;
            if (e.CommandName.Equals("Selected"))
            {

                txtSoHD.Text = gvr.Cells[1].Text;
                DataTable dtInfoHDChuaIn = new BWNhapHoaDonBanHang().dsInfoHoaDonChuaIn(ref error, txtSoHD.Text.Trim()).Tables[0];
                txtMaTVV.Text = dtInfoHDChuaIn.Rows[0]["MaTVV"].ToString();
                txtTenTVV.Text = dtInfoHDChuaIn.Rows[0]["TenTVV"].ToString();
                txtThongTinTVV.Text = dtInfoHDChuaIn.Rows[0]["ThongTinTVV"].ToString();
                txtNgayHD.Text = dtInfoHDChuaIn.Rows[0]["NgayHD"].ToString();
                get_ListChiTietHoaDon(gvr.Cells[1].Text, "get_ChiTietHoaDonTraChuaIn");
                txtMaTVV.Enabled = false;
                btnDelete.Visible = true;
                TabContainer1.ActiveTabIndex = 0;
            }
            else if (e.CommandName.Equals("btnPrinted"))
            {
                Session["MaHDPrinte"] = gvr.Cells[1].Text;
                new BWNhapHoaDonBanHang().UpdateHoaDonChuaIn(ref error, gvr.Cells[1].Text);
                FillGridHoaDonChuaIn();
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("window.open('" + Globals.ApplicationPath + "WebMaster/Administrator/TraHangDiShow/Print.aspx','PrintMe', 'height=900px,width=900px,scrollbars=1');");
                ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.UpdatePanel1.GetType(), "NewClientScript", sb.ToString(), true);

            }
        }
        catch
        {
            uscMsgBox1.AddMessage("Load dữ liệu không được.\n Error: " + error, uscMsgBox.enmMessageType.Error);
            return;
        }
    }
    protected void txtMaTVVFind_TextChanged(object sender, EventArgs e)
    {
        try
        {
            if (!txtMaTVVFind.Text.Equals(String.Empty))
            {
                string str = txtMaTVVFind.Text;
                int index = str.IndexOf("|");
                txtMaTVVFind.Text = str.Substring(0, index - 1);
                txtTenTVVFind.Text = str.Substring(index + 2, str.Length - index - 2);                
               
            }
        }
        catch
        { return; }
    }
    protected void ImageButtonFind_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            //txtTenTVVFind.Visible = false;
            BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
            DataTable dts = obj.dsFindHoaDonTVV(ref error, Session["SiteCode"].ToString(), txtMaTVVFind.Text.Trim(), 1, "I", txtFromDay.Text, txtToDay.Text).Tables[0];
            
            
           if (dts.Rows.Count > 0)
            {
                gvDonHangFind.DataSource = dts;
                gvDonHangFind.DataBind();

            }
            else
            {
                dts.Rows.Add(dts.NewRow());
                gvDonHangFind.DataSource = dts;
                gvDonHangFind.DataBind();

                int TotalColumns = gvDonHangChuaIn.Rows[0].Cells.Count;
                gvDonHangFind.Rows[0].Cells.Clear();
                gvDonHangFind.Rows[0].Cells.Add(new TableCell());
                gvDonHangFind.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                gvDonHangFind.Rows[0].Cells[0].Text = "Không có đơn hàng trong khoảng thời gian này.";
            }
        }
        catch(Exception ex)
        {
            uscMsgBox1.AddMessage(ex.Message, uscMsgBox.enmMessageType.Error);
            return;
        }
    }  
    protected void gvDonHangFind_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        try
        {
            GridViewRow gvr = ((Control)e.CommandSource).NamingContainer as GridViewRow;
            if (e.CommandName.Equals("Selected"))
            {                
                DataTable dtInfoHDChuaIn = new BWNhapHoaDonBanHang().dsInfoHoaDonTraHang(ref error, gvr.Cells[0].Text.Trim()).Tables[0];
                txtMaTVV.Text = dtInfoHDChuaIn.Rows[0]["MaTVV"].ToString();
                txtTenTVV.Text = dtInfoHDChuaIn.Rows[0]["TenTVV"].ToString();
                txtThongTinTVV.Text = dtInfoHDChuaIn.Rows[0]["ThongTinTVV"].ToString();
               
                get_ListChiTietHoaDon(gvr.Cells[0].Text,"get_ChiTietHoaDonTra");
                txtMaTVV.Enabled = false;
                GetDoanhSoTrongThangTVV(txtMaTVV.Text);
                TabContainer1.ActiveTabIndex = 0;
                txtSoHD.Text = "";
            }            
        }
        catch
        {
            uscMsgBox1.AddMessage("Load dữ liệu không được.\n Error: " + error, uscMsgBox.enmMessageType.Error);
            return;
        }
    }
    protected void txtMaTVV_TextChanged(object sender, EventArgs e)
    {
        try
        {
            if (!txtMaTVV.Text.Equals(String.Empty))
            {
                string str = txtMaTVV.Text;
                int index = str.IndexOf("|");
                txtMaTVV.Text = str.Substring(0, index - 1);
                txtTenTVV.Text = str.Substring(index + 2, str.Length - index - 2);
                BWNhapHoaDonBanHang obj = new BWNhapHoaDonBanHang();
                txtThongTinTVV.Text = obj.dsInfoTuVanVien(ref error, txtMaTVV.Text).Tables[0].Rows[0]["ThongTinTVV"].ToString();

                GetDoanhSoTrongThangTVV(txtMaTVV.Text);

            }
        }
        catch (Exception ex)
        {
            BCDataCenter.ClassWriteLogErr ob = new BCDataCenter.ClassWriteLogErr();
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            ob.ErrorLog(ex.Message, method);
        }
    }
}
